package com.ihuipao.game;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.health.connect.datatypes.units.Volume;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.ejlchina.okhttps.HTTP;
import com.ejlchina.okhttps.HttpResult;
import com.ejlchina.okhttps.Process;
import com.ejlchina.okhttps.gson.GsonMsgConvertor;
import com.google.android.material.snackbar.Snackbar;

import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.provider.Settings;
import android.util.Log;
import android.view.View;

import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.ihuipao.game.Objects.Photo;
import com.ihuipao.game.databinding.ActivityMainBinding;

import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;

public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration appBarConfiguration;
    private ActivityMainBinding binding;
    private static final String TAG = "PHOTO";
    private Map<String, String> fileMap = new HashMap<>();
    private Map<String, String> uploadMap = new HashMap<>();
    private static final int MSG_SHOW_DIR = 1;
    private static final int MSG_SHOW_TOTAL = 2;
    private static final int MSG_SHOW_UPLOAD = 3;

    private TextView textViewScanDir;
    private TextView textTotal;
    private TextView textUploaded;
    private TextView textUnupload;
    private LinearLayout layoutUsb;
    private ProgressBar progressUpload;
    private Button buttonUpload;
    private Button buttonTakephoto;
    private TextView textUploadFile;
    private boolean upload = false;
    private boolean scan = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        setSupportActionBar(binding.toolbar);

        buttonTakephoto = findViewById(R.id.button_takephoto);
        buttonUpload = findViewById(R.id.button_upload);
        textViewScanDir = findViewById(R.id.text_scan_dir);
        textTotal = findViewById(R.id.text_total);
        textUploaded = findViewById(R.id.text_uploaded);
        textUnupload = findViewById(R.id.text_unupload);
        layoutUsb = findViewById(R.id.layout_usb);
        textUploadFile = findViewById(R.id.text_uploadfile);
        progressUpload = findViewById(R.id.progress_upload);
        buttonTakephoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });

        buttonUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                upload("thumbnail");
            }
        });

        listenUsb();

        requestPermission();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//保持屏幕常亮，避免后台运行中断
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {

            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void listenUsb(){
        Log.e(TAG, "listenUsb: " + "监听" );
        Context context = MainActivity.this;
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
        filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
        filter.addDataScheme("file");
        context.registerReceiver(usbReceiver, filter);

        scanUsb();//默认扫描USB
    }

    BroadcastReceiver usbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.e(TAG, "onReceive: " + action );
            if(action.equals(Intent.ACTION_MEDIA_MOUNTED)){
                Log.e(TAG, "onReceive: " + "插卡" );
                layoutUsb.setVisibility(View.VISIBLE);
                scanUsb();
            }else if(action.equals(Intent.ACTION_MEDIA_UNMOUNTED)){
                Log.e(TAG, "onReceive: " + "U盘断开了" );
                layoutUsb.setVisibility(View.GONE);
            }
        }
    };

    /**
     * 遍历磁盘
     */
    private void scanUsb(){
        StorageManager storageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
        List<StorageVolume> volumeList = storageManager.getStorageVolumes();
        for (StorageVolume item: volumeList) {
            try {
                if(!item.getDirectory().getPath().contains("emulated") && item.getState().equals("mounted")){//内部目录包含emulated
                    layoutUsb.setVisibility(View.VISIBLE);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            scanFiles(item.getDirectory(), 1);
                        }
                    }).start();
                }
            }catch (Exception ex){

            }
        }
    }

    public void upload(String type){
        new Thread(new Runnable() {
            @Override
            public void run() {
                HTTP http = HTTP.builder().baseUrl("https://api.ihuipao.com/")
                        .addMsgConvertor(new GsonMsgConvertor())
                        .build();
                if(fileMap.size()>0){
                    for(String path : fileMap.keySet()){
                        try {
                            if(!FileUtils.isFileExists(path)){
                                continue;//文件不存在退出业务，例如卡松动导致的文件不存在
                            }
                            String size = FileUtils.getSize(path);
                            Photo item = new Photo(path);
                            if(item.isUpload(type)){
                                uploadMap.put(path, path);
                                continue;//避免重复上传
                            }
                            http.async("photo/upload")
                                    .addBodyPara("name", path)
                                    .addBodyPara("filename", path)
                                    .addBodyPara("md5", item.getMd5())
                                    .addBodyPara("make", item.getExif().getMake())
                                    .addBodyPara("origin_width", item.getWidth())
                                    .addBodyPara("origin_height", item.getHeight())
                                    .addBodyPara("uniqid", item.getExif().getUniqid())
                                    .addBodyPara("shoot_at", item.getExif().getDateTime())
                                    .addFilePara("file", type=="origin" ? item.getFile() : item.compress(MainActivity.this))
                                    .addBodyPara("type", type)
                                    .addBodyPara("albumid", "214")
                                    .addBodyPara("size", item.getLength())
                                    .addBodyPara("orientation", item.getExif().getOrientation())
                                    .addBodyPara("_token", "dc65J8YqVW1eXtomoO2jNx1NKrFhRWMjUqjbSvja")
                                    .stepBytes(10240)   // 设置每发送 1024 个字节执行一次进度回调（不设置默认为 8192）
                                    //     .stepRate(0.01)    // 设置每发送 1% 执行一次进度回调（不设置以 StepBytes 为准）
                                    .setOnProcess((Process process) -> {           // 上传进度回调
                                        //Log.e(TAG, "run: " + path );
                                        long doneBytes = process.getDoneBytes();   // 已发送字节数
                                        long totalBytes = process.getTotalBytes(); // 总共的字节数
                                        double rate = process.getRate();           // 已发送的比例
                                        boolean isDone = process.isDone();         // 是否发送完成
                                        //Log.e(TAG, "run: " + (isDone ? "成功" : "进行中")  + rate);
                                        item.setProgress((int) Math.round(rate*100));
                                        mHandler.obtainMessage(MSG_SHOW_UPLOAD, item).sendToTarget();
                                    })
                                    .setOnResponse((HttpResult httpResult) -> {
                                        if(httpResult.getStatus()==200){
                                            try {
                                                String body = httpResult.getBody().toString();
                                                JSONObject json = new JSONObject(body);
                                                if (json.optInt("code") == 200) {
                                                    ToastUtils.showShort("上传成功");
                                                    uploadMap.put(path, path);
                                                    item.setUpload(type);//置为已上传
                                                } else {
                                                    ToastUtils.showShort(json.getString("msg"));
                                                }
                                            }catch (Exception ex){
                                                ToastUtils.showShort(ex.getMessage());
                                            }
                                        }else{
                                            ToastUtils.showShort("网络错误");
                                        }
                                        mHandler.obtainMessage(MSG_SHOW_TOTAL).sendToTarget();
                                    })
                                    .post();
                        }catch (Exception ex){

                        }
                    }
                }
            }
        }).start();
    }

    /**
     * 压缩图片
     * @param path
     */
    private void compress(String path){

    }

    /**
     * 扫描图片文件列表
     * @param dir
     * @param depth
     */
    private void scanFiles(File dir, int depth){
        //Log.e(TAG, "scanFiles: " + dir.getPath() );
        if(dir.getPath().contains("$RECYCLE")){
            return;
        }

        if(dir.isHidden()){
            return;//隐藏目录不处理
        }
        FileUtils.listFilesInDir(dir,true);
        if(depth>=5){
            //Log.e(TAG, "scanFiles: " + "层级太深，退出" );
            //return;//最多遍历三级
        }

        depth++;
        if(dir.isDirectory()){
            mHandler.obtainMessage(MSG_SHOW_DIR, dir.getPath()).sendToTarget();
            File[] files = dir.listFiles();
            if(files==null){
                return;
            }

            for (File file: files) {
                if(file.isDirectory()){
                    scanFiles(file, depth);
                }else{
                    String filename = file.getPath().toLowerCase();//.substring(file.getPath().lastIndexOf(".")).toLowerCase();
                    if(filename.endsWith(".jpg") || filename.endsWith(".jpeg")){
                        fileMap.put(file.getPath(),file.getPath());
                        mHandler.obtainMessage(MSG_SHOW_TOTAL).sendToTarget();
                    }
                }
            }
        }
    }

    private void showProgress(){

    }

    private void upload(){
        if(upload){//上传中，暂停
            upload = false;
            buttonUpload.setText("开始上传");
        }else{
            upload = true;
            buttonUpload.setText("暂停上传");
        }

    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case MSG_SHOW_DIR:
                    String dir = msg.obj.toString();
                    textViewScanDir.setText(dir);
                    break;
                case MSG_SHOW_TOTAL:
                    int total = fileMap.size();
                    textTotal.setText(total + "");
                    textUploaded.setText(uploadMap.size() + "");
                    textUnupload.setText(fileMap.size()-uploadMap.size() + "");
                    break;
                case MSG_SHOW_UPLOAD:
                    Photo photo = (Photo) msg.obj;
                    textUploadFile.setText(photo.getPath());
                    progressUpload.setProgress(photo.getProgress());
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public boolean onSupportNavigateUp() {
        return true;
    }

    private void requestPermission(){

        XXPermissions xxPermissions = XXPermissions.with(MainActivity.this);

        if(!XXPermissions.isGranted(this, Permission.MANAGE_EXTERNAL_STORAGE)) {
                xxPermissions.permission(Permission.MANAGE_EXTERNAL_STORAGE);
        }
        Log.e(TAG, "requestPermission: " + Build.VERSION.SDK_INT );
        if(Build.VERSION.SDK_INT>=30){
            xxPermissions.permission(Permission.READ_MEDIA_IMAGES)
                    .permission(Permission.READ_MEDIA_AUDIO)
                    .permission(Permission.READ_MEDIA_VIDEO);
        }else{
            xxPermissions.permission(Permission.READ_EXTERNAL_STORAGE)
                    .permission(Permission.WRITE_EXTERNAL_STORAGE);
        }

                xxPermissions.request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(@NonNull List<String> permissions, boolean allGranted) {

                    }
                });
    }
}